from flask import current_app
from flask import g
from flask import redirect
from flask import render_template, jsonify
from flask import request

from info import constants, db
from info.models import Category, News
from info.moduels.profile import profile_blu
from info.utils.common import user_data_info
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route("/user_news_list")
@user_data_info
def user_news_list():
    """
    个人中心 -- 新闻列表
    :return:
    """
    # 获取参数
    page = request.args.get(g,"1")
    # 校验参数
    if not page:
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")

    total_page = 1
    content_page = 1
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")
    try:
        user = g.user
        news = News.query.filter(News.user_id == user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DBERR ,errmsg = "数据库查询错误")

    total_page = news.pages
    content_page = news.page
    news_s = news.items

    news_dict_li = []
    for news in news_s:
        news_dict_li.append(news.to_review_dict())
        print(news.status)

    data = {
        "total_page":total_page,
        "content_page":content_page,
        "news_list":news_dict_li
    }
    return render_template("news/user_news_list.html",data = data)


@profile_blu.route("/news_release",methods = ["POST","GET"])
@user_data_info
def news_release():
    # 新闻发布
    if request.method == "GET":
        # 获取新闻的分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.DBERR,errmsg = "数据查询错误")

        category_li = []
        for category in categories:
            category_li.append(category)
        # 删除最新字段
        category_li.pop(0)

        data = {
            "categories":category_li
        }
        return  render_template("news/user_news_release.html" ,data = data)

    # 1.获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    try:
        category_id = int(category_id)
    except Exception as e:
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    if not all ([title,category_id,digest,index_image,content]):
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")

    user = g.user
    news = News()
    # 新闻id
    news.user_id = user.id
    # 新闻主题
    news.title = title
    # 新闻分类id
    news.category_id = category_id
    # 新闻内容
    news.content = content
    # 新闻摘要
    news.digest = digest
    # 新闻的图片路径--保存全路径是因为,要在网页上显示--后期不用拼接
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    # 1代表审核中
    news.status = 1
    # 新闻来源
    news.source = "个人发布"
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DATAERR,errmsg = "数据插入错误")

    return jsonify(errno = RET.OK,errmsg = "OK")


@profile_blu.route("/collection")
@user_data_info
def user_collection():
    """
    个人中心--我的收藏
    :return:
    """
    # 获取参数
    page = request.args.get("p", 1)

    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 查询用户指定页数的收藏的新闻
    user = g.user

    news_list = []
    total_page = 1
    current_page = 1
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": news_dict_li
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route("/pass_info",methods = ["POST","GET"])
@user_data_info
def pass_info():
    """
    个人中心--修改密码
    :return:
    """
    if request.method == "GET":
        data = {

        }
        return render_template("news/user_pass_info.html",data = data)

    # 1.获取参数
    user = g.user
    old_password=request.json.get("old_password")
    new_password=request.json.get("new_password")
    print(old_password)
    if not all ([old_password,new_password]):
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    # 老密码正确,才能修改密码
    if user.check_password(old_password):
        try:
            user.password = new_password
        except Exception as e:
            current_app.logger.error(e)
            return  jsonify(errno = RET.DATAERR,errmsg = "数据修改错误")

    return jsonify(errno = RET.OK ,errmsg = "OK")


@profile_blu.route("/pic_info",methods = ["POST","GET"])
@user_data_info
def pic_info():
    """
    个人中心--头像资料
    :return:
    """
    # 如果是GET请求,那么就渲染模板
    user = g.user
    if request.method == "GET":
        data = {
            "user":user.to_dict()
        }
        return  render_template("news/user_pic_info.html",data = data)

    # 1.获取参数
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.NODATA,errmsg = "无数据")

     # 2.使用创建的7牛云来保存图片地址
    try:
        key = storage(avatar)
    except Exception as e:
        return jsonify(errno = RET.THIRDERR,errmsg = "图片上传失败")
    user.avatar_url = key

    # 响应--将图片地址返回给前端--以便跟新相应图片
    return jsonify(errno = RET.OK,errmsg = "OK",data = {"avatar_url":constants.QINIU_DOMIN_PREFIX + key })




@profile_blu.route("/base_info",methods = ["POST","GET"])
@user_data_info
def user_base_info():
    """
    个人中心--基本资料
    :return:
    """
    if request.method == "GET":
        data = {
            "user":g.user.to_dict()
        }
        return  render_template("news/user_base_info.html",data = data)

    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    if not all([nick_name,signature,gender]):
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    if gender not in ("WOMAN","MAN"):
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")

    user = g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno = RET.OK,errmsg = "OK")


@profile_blu.route("/user_info")
@user_data_info
def user_info():
    """
    个人中心主页
    :return:
    """
    user = g.user
    # 用户未登陆--重定向到首页
    if not user:
        return redirect("/")
    data = {
        "user":user.to_dict()
    }
    return  render_template("news/user.html",data = data)